package _剑指offer.二叉树;

import util.TreeNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 每层打印到一行： 将本层全部节点打印到一行，并将下一层全部节点加入队列，以此类推，即可分为多行打印。
 */
public class _32_2_从上到下打印二叉树 {
    @Test
    public void main() {
        Integer[] input = new Integer[]{3,9,20,null,null,15,7};
        TreeNode root = TreeNode.getTreeFromArray(input);
        List<List<Integer>> results = levelOrder(root);
        System.out.println("[");
        results.forEach(list -> System.out.println("  " + list + " ,"));
        System.out.println("]");
    }
    
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        
        List<List<Integer>> answer = new ArrayList<>();
        while (!queue.isEmpty()) {
            int n = queue.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            answer.add(temp);
        }
        return answer;
    }
}
